package com.lzh.config;

import com.lzh.pojo.Teacher;
import com.lzh.service.TeacherService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author reborn
 * @create 2020/6/1-22:57
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    TeacherService teacherService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Teacher current = (Teacher) subject.getPrincipal();
        if (current.getPerms().equals("root")){
            info.addStringPermission("teacher");
        }
        info.addStringPermission(current.getPerms());

        return info;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken= (UsernamePasswordToken) authenticationToken;

        Teacher teacher = teacherService.selectZh(userToken.getUsername());
        if (teacher==null){ // 没有这个人
            return  null;  //UnknownAccountException
        }

        return new SimpleAuthenticationInfo(teacher,teacher.getPwd(),"");
    }
}
